package com.relatev.minecraft.TRMobAPI;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

public class Networker
        implements Runnable, Listener {
    
    public static String BcMessage;
    private static Networker Instance;
    
    public static void init() {
        Instance = new Networker();
        Bukkit.getScheduler().runTaskAsynchronously(TRMobAPI.getAPI(), Instance);
        Bukkit.getPluginManager().registerEvents(Instance, TRMobAPI.getAPI());
    }
    
    @Override
    public void run() {
        try {
            //整体获取
            File URLLogFile = new File(TRMobAPI.getAPI().getDataFolder(), "URLLog");
            Networker.DowloadFile("http://urllog.relatev.com/files/TRMobAPI/NetWorker.yml", URLLogFile);
            YamlConfiguration URLLog = YamlConfiguration.loadConfiguration(URLLogFile);
            //检查插件并下载新版本
            if (TRMobAPI.getAPI().getTRConfigManager().CoreConfig.getBoolean("AutoUpdate") == true) {
                TRMobAPI.getAPI().getLogger().info("正在检查新版本插件，请稍等...");
                int NewVersion = URLLog.getInt("UpdateVersion");
                int NowVersion = Versioning.Version;
                if (NewVersion > NowVersion) {
                    TRMobAPI.getAPI().getLogger().info("插件检测到新版本 " + NewVersion + " 正在下载更新...");
                    Method method = TRMobAPI.getAPI().getClass().getSuperclass().getDeclaredMethod("getFile");
                    method.setAccessible(true);
                    File pluginfile = (File) method.invoke(TRMobAPI.getAPI());
                    Networker.DowloadFile("http://urllog.relatev.com/files/TRMobAPI/TRMobAPI.jar", pluginfile);
                    TRMobAPI.getAPI().getLogger().info("插件更新版本下载完成！正在重启服务器！");
                    Bukkit.shutdown();
                } else {
                    TRMobAPI.getAPI().getLogger().info("TRMobAPI插件工作良好，暂无新版本检测更新。");
                }
            }
            //云公告
            TRMobAPI.getAPI().getLogger().info("正在读取云公告...");
            BcMessage = URLLog.getString("BcMessage");
            //完成提示
            TRMobAPI.getAPI().getLogger().info("全部网络工作都读取完毕了...");
        } catch (IOException ex) {
            TRMobAPI.getAPI().getLogger().info("插件在自动更新工作时出现错误!可能是无法连接到更新服务器!");
//            Logger.getLogger(BKNetworker.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            Logger.getLogger(Networker.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private static void DowloadFile(String urlStr, File savefile) throws IOException {
        if (savefile.exists() == true) {
            savefile.delete();
        }
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒  
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误  
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流  
        InputStream inputStream = conn.getInputStream();
        //获取自己数组  
        byte[] getData = readInputStream(inputStream);

        //文件保存位置  
        File file = savefile;
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    
    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
    
    @EventHandler
    public void CheckUpdateOn(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        if (player.hasPermission("TRMobAPI.admin")) {
            if (TRMobAPI.getAPI().getTRConfigManager().CoreConfig.getBoolean("AutoUpdate") == false) {
                player.sendMessage("§a[TRMobAPI]§b提示：§cTRMobAPI 插件的自动更新没有打开，可能导致部分附属无法工作。");
                player.sendMessage("§e请输入/trm updateon 来开启这个功能！新的版本往往优化更好，支持更多附属插件！");
            }
            if (BcMessage != null) {
                player.sendMessage("§a[TRMobAPI]§r" + BcMessage);
            }
        }
    }
}
